<template>
  <el-card class="h-full">
    <template #header>
      <div class="flex items-center justify-between">
        <div class="inline-flex items-center leading-none">
          <h2 class="text-xl font-semibold text-gray-800">生成历史</h2>
          <el-tooltip content="最多显示近100条记录" placement="top">
            <el-icon :size="16" class="ml-1 align-middle text-gray-400 hover:text-gray-600">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
        </div>
        <div class="flex space-x-2">
          <el-button type="danger" plain @click="clearHistory" :loading="clearing">
            <el-icon>
              <Delete />
            </el-icon>
            清空历史
          </el-button>
          <el-button type="primary" plain @click="loadHistory" :loading="loading">
            <el-icon>
              <Refresh />
            </el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </template>

    <div v-if="loading" class="text-center py-8">
      <el-icon class="animate-spin text-blue-600 text-2xl">
        <Loading />
      </el-icon>
      <p class="text-gray-500 mt-2">加载中...</p>
    </div>

    <div v-else-if="historyList.length === 0" class="text-center py-8">
      <el-icon class="text-gray-400 text-4xl">
        <Document />
      </el-icon>
      <p class="text-gray-500 mt-2">暂无生成记录</p>
    </div>


    <div v-else class="space-y-4 flex-1">
      <el-scrollbar height="460px">
        <div v-for="item in historyList" :key="item.id"
          class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
          <div class="flex items-start justify-between">
            <div class="flex-1">
              <div class="flex items-center space-x-2 mb-2">
                <el-tag size="small" :type="getCharTypeColor(item.char_type)">
                  {{ getCharTypeLabel(item.char_type) }}
                </el-tag>
                <span class="text-sm text-gray-500">
                  长度: {{ item.length }}
                </span>
                <span class="text-sm text-gray-500">
                  {{ formatDate(item.created_at) }}
                </span>
              </div>
              <div class="mb-3">
                <el-text class="inline-block w-[300px] mb-2 align-middle" truncated :title="item.generated_string">
                  {{ item.generated_string }}
                </el-text>
                <el-button class="ml-3 align-middle" size="small" @click="copyItem(item.generated_string)"
                  :icon="DocumentCopy">
                  复制
                </el-button>
              </div>

              <div v-if="item.prefix || item.suffix" class="text-sm text-gray-600 space-y-1">
                <div v-if="item.prefix" class="truncate" :title="item.prefix">
                  <span class="font-medium">前缀:</span> {{ item.prefix }}
                </div>
                <div v-if="item.suffix" class="truncate" :title="item.suffix">
                  <span class="font-medium">后缀:</span> {{ item.suffix }}
                </div>
              </div>
            </div>

            <!-- 右侧按钮区域已移动到文本后面 -->
          </div>
        </div>
      </el-scrollbar>
      <!-- 移除分页：最多显示近100条 -->
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Refresh, Document, DocumentCopy, Loading } from '@element-plus/icons-vue'
import { getHistory, clearHistory } from '../services/api'
import { CHAR_TYPES } from '../utils/constants'

const historyList = ref([])
const loading = ref(false)
const clearing = ref(false)

// 获取字符类型标签
const getCharTypeLabel = (type) => {
  const found = CHAR_TYPES.find(t => t.value === type)
  return found ? found.label : type
}

// 获取字符类型颜色
const getCharTypeColor = (type) => {
  const colors = {
    digits: '',
    letters: 'success',
    digits_letters: 'warning',
    symbols: 'danger',
    digits_letters_symbols: 'warning',
    chinese: 'info',
    custom: 'info'
  }
  return colors[type] || ''
}

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 加载历史记录
const loadHistory = async () => {
  loading.value = true
  try {
    // 请求最多100条，或在前端进行截取
    const response = await getHistory(1, 100)
    historyList.value = Array.isArray(response.history)
      ? response.history.slice(0, 100)
      : []
  } catch (error) {
    // 全局拦截器已提示，这里无需重复弹窗
  } finally {
    loading.value = false
  }
}

// 清空历史记录
const clearHistoryHandler = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有历史记录吗？此操作不可恢复。',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    clearing.value = true
    await clearHistory()
    ElMessage.success('历史记录已清空')
    await loadHistory()
  } catch (error) {
    if (error !== 'cancel') {
      // 全局拦截器已提示，这里无需重复弹窗
    }
  } finally {
    clearing.value = false
  }
}

// 复制单个项目
const copyItem = async (text) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('已复制到剪贴板')
  } catch (err) {
    const textArea = document.createElement('textarea')
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('已复制到剪贴板')
  }
}

// 无分页

// 监听历史更新事件
const handleHistoryUpdate = () => {
  loadHistory()
}

onMounted(() => {
  loadHistory()
  window.addEventListener('history-updated', handleHistoryUpdate)
})

onUnmounted(() => {
  window.removeEventListener('history-updated', handleHistoryUpdate)
})

defineExpose({
  loadHistory
})
</script>